package com.jt.www.admin.market.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.jt.www.admin.market.service.CommissionService;
import com.jt.www.admin.order_pc.service.ExportConfigService;
import com.jt.www.domain.bo.CommissionBO;
import com.jt.www.domain.bo.MarketerUserRoleBO;
import com.jt.www.domain.dto.CommissionPushDownDTO;
import com.jt.www.domain.enums.common.ExportChannelTypeEnum;
import com.jt.www.domain.po.CommissionPush;
import com.jt.www.domain.po.ExportConfigEntity;
import com.jt.www.domain.qo.CommissionPushQO;
import com.jt.www.domain.qo.CommissionQO;
import com.jt.www.domain.qo.PolCommissionPushParam;
import com.jt.www.domain.vo.CommissionPushListVO;
import com.jt.www.domain.vo.CommissionVO;
import com.jt.www.model.reps.GenericDataResponse;
import com.jt.www.model.reps.GenericListResponse;
import com.jt.www.util.excel.CsvExportUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * 保存佣金配置
 * Created by shaoyn on 2020/04/10.
 */
@Api(value = "保存佣金配置相关接口", tags = {"COMMISSION-INFO-API"}, description = "保存佣金配置相关接口")
@RestController
@RequestMapping(value = "/commission")
public class CommissionController {

    public static final Logger log = LoggerFactory.getLogger(CommissionController.class);

    private static final String JTPF_USER_ID = "jtpf.userId";

    @Autowired
    private CommissionService commissionService;

    @Autowired
    private ExportConfigService exportConfigService;

    /**
     * 保存佣金配置
     *
     * @return
     */
    @ApiOperation(value = "保存佣金配置", notes = "保存佣金配置", httpMethod = "POST")
    @PostMapping(value = "/saveCommission", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity saveCommission(@RequestBody CommissionBO commissionBO) {
        //如果产品信息为空或 产品编码为空 返回报错信息
        if (null == commissionBO.getCommissionProduct() ||
                StringUtils.isBlank(commissionBO.getCommissionProduct().getProductCode())) {
            return GenericDataResponse.errorWithMsg("产品信息不能为空!");
        }
        int n;
        try {
            n = commissionService.saveCommission(commissionBO);
        } catch (Exception e) {
            return GenericDataResponse.errorWithMsg(e.getMessage());
        }
        if (n > 0) {
            return GenericDataResponse.ok();
        }
        return GenericDataResponse.errorWithMsg("保存失败!");
    }

    /**
     * 修改佣金配置
     *
     * @return
     */
    @ApiOperation(value = "修改佣金配置", notes = "修改佣金配置", httpMethod = "POST")
    @PostMapping(value = "/updateCommission", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity updateCommission(@RequestBody CommissionBO commissionBO) {
        if (commissionService.updateCommission(commissionBO) > 0) {
            return GenericDataResponse.ok();
        }
        return GenericDataResponse.errorWithMsg("没有修改记录!");
    }

    /**
     * 删除佣金配置
     *
     * @return
     */
    @ApiOperation(value = "删除佣金配置", notes = "删除佣金配置", httpMethod = "POST")
    @PostMapping(value = "/deleteCommission/{id}", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity deleteCommission(@ApiParam(value = "产品配置表id", required = true) @PathVariable Long id) {
        if (commissionService.deleteCommission(id) > 0) {
            return GenericDataResponse.ok();
        }
        return GenericDataResponse.errorWithMsg("没有相关记录!");
    }

    /**
     * 查询佣金配置列表
     *
     * @return
     */
    @ApiOperation(value = "查询佣金配置列表", notes = "查询佣金配置列表", httpMethod = "POST")
    @PostMapping(value = "/queryCommission", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<GenericListResponse<CommissionVO>> queryCommission(@RequestBody CommissionQO commissionQO) {
        return commissionService.queryCommission(commissionQO);
    }

    /**
     * 查询佣金配置详情
     *
     * @return
     */
    @ApiOperation(value = "查询佣金配置详情", notes = "查询佣金配置详情", httpMethod = "POST")
    @PostMapping(value = "/queryCommissionDetails/{id}", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<GenericListResponse<CommissionBO>> queryCommissionDetails(@ApiParam(value = "产品配置表id", required = true) @PathVariable Long id) {
        return commissionService.queryCommissionDetails(id);
    }


    /**
     * 批单佣金推送至销管
     *
     * @return
     */
    @ApiOperation(value = "批单佣金推送至销管", notes = "批单佣金推送至销管", httpMethod = "POST")
    @PostMapping(value = "/createPolCommissionPush", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity createPolCommissionPush(@RequestBody PolCommissionPushParam polCommissionPushParam) {
        String logId = "PolCommission_" + System.currentTimeMillis();
        if (null != commissionService.createPolCommissionPush(logId,
                polCommissionPushParam.getApplyNo(), polCommissionPushParam.getEndorsementNo(), polCommissionPushParam.getUserCode())) {
            return GenericDataResponse.ok();
        }

        return GenericDataResponse.ok();
    }


    /**
     * 查询业绩列表
     *
     * @return
     */
    @ApiOperation(value = "查询业绩列表", notes = "查询业绩列表", httpMethod = "POST")
    @PostMapping(value = "/queryCommissionPushListVO", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity<GenericListResponse<CommissionPushListVO>> queryCommissionPushListVO(@RequestBody CommissionPushQO commissionPushQO) {
        return commissionService.queryCommissionPushListVO(commissionPushQO);
    }

    @ApiOperation(value = "导出业绩列表", notes = "导出业绩列表")
    @GetMapping(value = "/downCommissionPushListVO", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public void downCommissionPushListVO(CommissionPushQO commissionPushQO, HttpServletResponse response) {
        String findCode = "EDU_downCommissionPushListVO_" + System.currentTimeMillis();
        OutputStream os = null;
        try {
            //查询导出配置
            ExportConfigEntity exportConfigEntity = exportConfigService.getExportConfig(ExportChannelTypeEnum.COMMISSION_MANAGE.getCode());
            if (null == exportConfigEntity) {
                return;
            }
            String fileName = exportConfigEntity.getFileName();

            os = response.getOutputStream();
            CsvExportUtil.responseSetProperties(fileName, response);
            //模板位置
            String titles = exportConfigEntity.getTitles();
            CsvExportUtil.setTitles(titles, os);
            List<CommissionPush> appList;
            int pn = 1;
            commissionPushQO.setPn(pn);
            commissionPushQO.setPs(CsvExportUtil.MAX_PAGE_SIZE);
            String[] keyArr = exportConfigEntity.getKeyArr().split(",");

            //分批查询并生成数据插入到导出文件中
            while (CollectionUtils.isNotEmpty(appList = commissionService.downCommissionPushListVO(commissionPushQO).getBody().getList())) {
                List list = Lists.transform(appList, (Function<CommissionPush, Object>) commissionPush -> new CommissionPushDownDTO(commissionPush));
                CsvExportUtil.doExport(list, keyArr, os);
                commissionPushQO.setPn(++pn);
                if (commissionPushQO.getPs() > appList.size()) {
                    break;
                }
            }
        } catch (Exception e) {
            log.error("{}导出{}发生错误:", findCode, e);
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                }
            }
        }
    }

    /**
     * 查询业绩列表-获得用户查询限制
     *
     * @return
     */
    @ApiOperation(value = "查询业绩列表-获得用户查询限制", notes = "查询业绩列表-获得用户查询限制", httpMethod = "GET")
    @GetMapping(value = "/queryCommissionRole")
    public ResponseEntity<GenericDataResponse<MarketerUserRoleBO>> queryCommissionRole(HttpServletRequest request) {
        String userCode = request.getHeader(JTPF_USER_ID);
        if (StringUtils.isBlank(userCode)) {
            return GenericDataResponse.errorWithMsg("无用户信息!", MarketerUserRoleBO.class);
        }

        MarketerUserRoleBO marketerUserRoleBO;
        try {
            marketerUserRoleBO = commissionService.queryCommissionRole(userCode);
            if (null == marketerUserRoleBO) {
                return GenericDataResponse.errorWithMsg("用户无查询权限", MarketerUserRoleBO.class);
            }
        } catch (Exception e) {
            return GenericDataResponse.errorWithMsg(e.getMessage(), MarketerUserRoleBO.class);
        }

        //得到权限 返回
        return GenericDataResponse.okWithData(marketerUserRoleBO);
    }


    /**
     * 查询是否配置佣金
     *
     * @return
     */
    @ApiOperation(value = "查询是否配置佣金", notes = "查询是否配置佣金", httpMethod = "GET")
    @GetMapping(value = "/isHasCommission", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity isHasCommission(@ApiParam(value = "产品编码", required = true) @RequestParam String productCode) {
        if (StringUtils.isBlank(productCode)) {
            return GenericDataResponse.errorWithMsg("产品编码不能为空!");
        }
        return GenericDataResponse.okWithData(commissionService.isHasCommission(productCode));
    }

    /**
     * 保单佣金推送至销管
     *
     * @return
     */
    @ApiOperation(value = "保单佣金推送至销管", notes = "保单佣金推送至销管", httpMethod = "GET")
    @GetMapping(value = "/createInsCommissionPush", produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
    public ResponseEntity createInsCommissionPush(@ApiParam(value = "投保单号(逗号分割)", required = true) @RequestParam String appCodes) {
        long time = System.currentTimeMillis();
        for (String appCode : appCodes.split(",")) {
            String logId = "createInsCommissionPush_" + appCode + "_" + time;
            CommissionPush commissionPush = commissionService.createInsCommissionPush(logId, appCode);
            log.info("{} 生成的佣金推送：{}", logId, JSON.toJSONString(commissionPush));
        }
        return GenericDataResponse.ok();
    }


}
